package main

import (
	"encoding/json"
	"fmt"
	"time"
	"math/rand"
	"golang.org/x/net/websocket"

	"log"

	"net/http"
)

type Info struct {
	Index     int         `json:"index"`
	SCL       float64     `json:"SCL"`
	SCRvalues []SCRvalues `json:"SCRvalues"`
}
type SCRvalues struct {
	Index int     `json:"index"`
	Value float64 `json:"value"`
}

func Echo(ws *websocket.Conn) {

	var err error

	for {

		var reply string

		//websocket接受信息

		if err = websocket.Message.Receive(ws, &reply); err != nil {

			fmt.Println("receive failed:", err)

			break

		}

		fmt.Println("reveived from client: " + reply)

		msg := "received:" + reply

		fmt.Println("send to client:" + msg)
		ints := 484
		
		//这里是发送消息
		for {
			time.Sleep(1 * time.Second)
			ints ++ 
			SCLs := randFloats()
			jsons := Info{
				Index:     ints,
				SCL:       SCLs,
				SCRvalues: make([]SCRvalues, 0),
			}
			jsonStr, err := json.Marshal(jsons)
			if err !=nil{
				log.Println("err",err)
			}
			if err = websocket.Message.Send(ws, string(jsonStr)); err != nil {
				fmt.Println("send failed:", err)
				break

			}
		}

	}

}
func randFloats() float64 {
    return  1 + rand.Float64() * (10 - 1)
}
func main() {

	//html页面
	http.Handle("/", http.FileServer(http.Dir("web/")))
	//接受websocket的路由地址
	http.Handle("/websocket", websocket.Handler(Echo))
	if err := http.ListenAndServe(":1234", nil); err != nil {

		log.Fatal("ListenAndServe:", err)
	}
	log.Println("端口号1234")

}
